<template>
  <div class="projects-container">
    <div class="projects-header">
      <h2>慈善项目列表</h2>
      <el-button type="primary" @click="handleCreateProject">
        <el-icon><Plus /></el-icon>新建项目
      </el-button>
    </div>
    <el-card class="projects-content">
      <el-table :data="projectList" v-loading="loading" border>
        <el-table-column prop="id" label="项目ID" width="80" />
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="description" label="项目描述" show-overflow-tooltip />
        <el-table-column prop="targetAmount" label="目标金额" width="120">
          <template #default="{ row }">
            <span>{{ row.targetAmount }}元</span>
          </template>
        </el-table-column>
        <el-table-column prop="currentAmount" label="已筹金额" width="120">
          <template #default="{ row }">
            <span>{{ row.currentAmount }}元</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleViewDetail(row.id)">
                <el-icon><View /></el-icon>详情
              </el-button>
              <el-button type="primary" link @click="handleDonate(row)" :disabled="row.status !== 1">
                <el-icon><Money /></el-icon>捐赠
              </el-button>
              <el-button type="primary" link @click="handleVolunteer(row)" :disabled="row.status !== 1">
                <el-icon><User /></el-icon>志愿
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 捐赠对话框 -->
    <el-dialog v-model="donateDialogVisible" title="项目捐赠" width="500px">
      <el-form :model="donateForm" :rules="donateRules" ref="donateFormRef" label-width="80px">
        <el-form-item label="项目名称">
          <span>{{ currentProject?.name }}</span>
        </el-form-item>
        <el-form-item label="捐赠金额" prop="amount">
          <el-input-number
            v-model="donateForm.amount"
            :min="1"
            :max="99999"
            :precision="2"
            :step="10"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="留言" prop="message">
          <el-input
            v-model="donateForm.message"
            type="textarea"
            :rows="3"
            placeholder="请输入留言（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="donateDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="donateLoading" @click="submitDonate">确认捐赠</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const projectList = ref([])

// 项目状态
const getStatusType = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: 'info',    // 待审核
    1: 'success',  // 进行中
    2: 'warning',  // 已完成
    3: 'danger'    // 已关闭
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: number) => {
  const statusMap: { [key: number]: string } = {
    0: '待审核',
    1: '进行中',
    2: '已完成',
    3: '已关闭'
  }
  return statusMap[status] || '未知'
}

// 获取项目列表
const getProjectList = async () => {
  loading.value = true
  try {
    // TODO: 调用后端API获取项目列表
    // 模拟数据
    const mockData = Array.from({ length: 10 }, (_, index) => ({
      id: index + 1,
      name: `测试项目${index + 1}`,
      description: '这是一个测试项目的描述信息',
      targetAmount: 100000,
      currentAmount: Math.floor(Math.random() * 100000),
      status: Math.floor(Math.random() * 4)
    }))
    projectList.value = mockData
    total.value = 100
  } catch (error) {
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getProjectList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getProjectList()
}

// 项目操作
const handleCreateProject = () => {
  // TODO: 实现创建项目功能
  ElMessage.info('创建项目功能开发中')
}

const handleViewDetail = (id: number) => {
  router.push(`/projects/${id}`)
}

// 捐赠相关
const donateDialogVisible = ref(false)
const donateLoading = ref(false)
const donateFormRef = ref<FormInstance>()
const currentProject = ref<any>(null)

const donateForm = reactive({
  amount: 10,
  message: ''
})

const donateRules: FormRules = {
  amount: [
    { required: true, message: '请输入捐赠金额', trigger: 'blur' },
    { type: 'number', min: 1, message: '金额必须大于0', trigger: 'blur' }
  ]
}

const handleDonate = (project: any) => {
  currentProject.value = project
  donateForm.amount = 10
  donateForm.message = ''
  donateDialogVisible.value = true
}

const submitDonate = async () => {
  if (!donateFormRef.value) return
  
  await donateFormRef.value.validate((valid, fields) => {
    if (valid) {
      donateLoading.value = true
      // TODO: 实现捐赠逻辑
      setTimeout(() => {
        donateLoading.value = false
        donateDialogVisible.value = false
        ElMessage.success('捐赠成功')
        getProjectList()
      }, 1000)
    }
  })
}

// 志愿者相关
const handleVolunteer = (project: any) => {
  // TODO: 实现志愿者报名功能
  ElMessage.info('志愿者报名功能开发中')
}

onMounted(() => {
  getProjectList()
})
</script>

<style lang="scss" scoped>
.projects-container {
  .projects-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
    }
  }

  .projects-content {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>